package com.ljd.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.ljd.service.FileService;
import com.ljd.util.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(MultipartFile file) throws IOException {
        // 获取阿里云存储相关常量
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        // 创建oss实例
        OSS oss = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
//获取上传的文件流
        InputStream inputStream = file.getInputStream();

        String filename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("_", "");
        String newName = filename.substring(filename.lastIndexOf("."));
        filename = uuid +newName;

        String datePath = new DateTime().toString("yyyy/MM/dd");

        filename = datePath+"/"+filename;

// 上传文件
        oss.putObject(bucketName,filename,inputStream);


// 关闭OSSClient。
        oss.shutdown();
        //
        String url = "https://"+bucketName+"."+endPoint+"/"+filename;
        return url;
    }
}
